package org.example.java.ref;

import java.lang.ref.*;

/**
 * Created by Juntao.Zhang on 3/20/15.
 */
public class UseReferenceQueue {
  private static class ReferenceObject {
    @Override
    protected void finalize() throws Throwable {
      System.out.println("finalize 被调用");
      super.finalize();
    }

    public static void main(String[] args) {
      ReferenceQueue<ReferenceObject> queue = new ReferenceQueue<>();
      ReferenceObject object = new ReferenceObject();
//      PhantomReference<ReferenceObject> reference = new PhantomReference<>(object, queue);
      WeakReference<ReferenceObject> reference = new WeakReference<>(object, queue);
      object = null;
      Reference<? extends ReferenceObject> ref;
      while ((ref = queue.poll()) == null) {
        System.gc();
      }
      reference.clear();
      System.out.println(ref==reference);
      System.out.println("end");
    }
  }
}
/**
 true
 end
 finalize 被调用
 */
